package com.wedo.book.service;

import com.wedo.book.mapper.CategoryMapper;
import com.wedo.book.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@CacheConfig(cacheNames = "category")
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 添加分类
     * @return
     */
    @Cacheable(key = "'queryCategories'")
    public List<Category> queryCategories() {
        return this.categoryMapper.selectAll();
    }

    /**
     * 添加分类
     * @param category
     */
    @CacheEvict(value = "category", allEntries=true)
    public void addCategory(Category category) {
        // category
        category.setId(null);
        this.categoryMapper.insertSelective(category);
    }

    /**
     * 删除分类
     * @param id
     */
    @Transactional
    @CacheEvict(value = "category", allEntries=true)
    public void deleteCategory(Long id) {
        // 删除分类表
        this.categoryMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改分类
     * @param category
     */
    @Transactional
    @CacheEvict(value = "category", allEntries=true)
    public void updateCategory(Category category) {
        this.categoryMapper.updateByPrimaryKey(category);
    }

    /**
     * 根据图书id查找分类
     * @param bid
     * @return
     */
    @Cacheable(key = "'queryCategoryByBid'+#bid")
    public List<Category> queryCategoryByBid(Long bid) {
        return this.categoryMapper.queryCategoryByBid(bid);
    }

    /**
     * 根据分类id查询分类信息
     * @param cid
     * @return
     */
    @Cacheable(key = "'queryCategoryById'+#cid")
    public Category queryCategoryById(Long cid) {
        return this.categoryMapper.selectByPrimaryKey(cid);
    }
}
